#!/bin/bash
# Usable tylemp.sh on Debian 9.
# Version: Stable-20180220

########################################################################
# Core Functions
########################################################################
function die {
	echo "ERROR: $1" > /dev/null 1>&2
	exit 1
}

function check_sanity {
	# Do some sanity checking.
	if [ $(/usr/bin/id -u) != "0" ]
	then
		die 'Must be run by root user'
	fi

	if [ ! -f /etc/debian_version ]
	then
		die "Distribution is not supported"
	fi
}

function print_info {
	echo -n -e '\e[1;36m'
	echo -n $1
	echo -e '\e[0m'
}

function print_warn {
	echo -n -e '\e[1;33m'
	echo -n $1
	echo -e '\e[0m'
}

function check_remove {
	if [ -n "`which "$1" 2>/dev/null`" ]
	then
		DEBIAN_FRONTEND=noninteractive apt-get -q -y remove --purge "$2"
		print_info ""
		print_info "$2 removed"
		print_info ""
	else
		print_info ""
		print_warn "$2 is not installed"
		print_info ""
	fi
}

function check_install {
	if [ -z "`which "$1" 2>/dev/null`" ]
	then
		executable=$1
		shift
		while [ -n "$1" ]
		do
		DEBIAN_FRONTEND=noninteractive apt-get -q -y  install "$1"
		print_info ""
		print_info "$1 installed for $executable"
		print_info ""
		shift
		done
	else
		print_info ""
		print_warn "$2 already installed"
		print_info ""
	fi
}

function remove_unneeded {
	# Remove rsyslogd, which allocates ~30MB privvmpages on an OpenVZ system,
	# which might make some low-end VPS inoperatable. We will do this even
	# before running apt-get update.
	check_remove /usr/sbin/rsyslogd rsyslog

	# Some Debian have portmap installed. We don't need that.
	check_remove /sbin/portmap portmap

	# Other packages that seem to be pretty common in standard OpenVZ
	# templates.
	check_remove /usr/sbin/named bind9
	check_remove /usr/sbin/nscd nscd
	check_remove /usr/sbin/apache2 'apache2*'
	check_remove /usr/sbin/smbd 'samba*'

	# Need to stop sendmail as removing the package does not seem to stop it.
	if [ -f /usr/lib/sm.bin/smtpd ]
	then
		invoke-rc.d sendmail stop
		check_remove /usr/lib/sm.bin/smtpd 'sendmail*'
	fi
}

function update_upgrade {
	apt-get -q -y update
	apt-get -q -y upgrade
	apt-get -q -y dist-upgrade
}

function get_domain_name() {
	# Getting rid of the lowest part.
	domain=${1%.*}
	lowest=`expr "$domain" : '.*\.\([a-z][a-z]*\)'`
	case "$lowest" in
	com|net|org|gov|edu|co|top|cn|info|me|us|club|xyz|tk|io|sh|mobi|pro|name|biz|red|vip|app|life|online|shop|site|today|cc|de|be|in|it|jp|tokyo|osaka|tw|hk|uk|xxx|ltd|fun|so)
		domain=${domain%.*}
		;;
	esac
	lowest=`expr "$domain" : '.*\.\([a-z][a-z]*\)'`
	[ -z "$lowest" ] && echo "$domain" || echo "$lowest"
}

function get_password() {
	# Check whether our local salt is present.
	SALT=/var/lib/radom_salt
	if [ ! -f "$SALT" ]
	then
		head -c 512 /dev/urandom > "$SALT"
		chmod 400 "$SALT"
	fi
	password=`(cat "$SALT"; echo $1) | md5sum | base64`
	echo ${password:0:18}
}

########################################################################
# Core Utilities
########################################################################
function install_utilities {
	apt-get -q -y install libc6 perl debconf dialog bsdutils apt wget bc curl nano make zip unzip dselect dpkg apt-utils
	update_upgrade
}

function install_exim4 {
	check_install mail exim4
	if [ -f /etc/exim4/update-exim4.conf.conf ]
	then
		sed -i \
		"s/dc_eximconfig_configtype='local'/dc_eximconfig_configtype='internet'/" \
		/etc/exim4/update-exim4.conf.conf
		invoke-rc.d exim4 restart
	fi
}

function install_syslogd {
	# We just need a simple vanilla syslogd. Also there is no need to log to
	# so many files (waste of fd). Just dump them into
	# /var/log/(cron/mail/messages)
	check_install /usr/sbin/syslogd inetutils-syslogd
	invoke-rc.d inetutils-syslogd stop

	for file in /var/log/*.log /var/log/mail.* /var/log/debug /var/log/syslog
	do
		[ -f "$file" ] && rm -f "$file"
	done
	for dir in fsck news
	do
		[ -d "/var/log/$dir" ] && rm -rf "/var/log/$dir"
	done

	cat > /etc/syslog.conf <<END
*.*;mail.none;cron.none		-/var/log/messages
cron.*						-/var/log/cron
mail.*						-/var/log/mail
END

	[ -d /etc/logrotate.d ] || mkdir -p /etc/logrotate.d
	cat > /etc/logrotate.d/inetutils-syslogd <<END
/var/log/cron
/var/log/mail
/var/log/messages {
	rotate 4
	weekly
	missingok
	notifempty
	compress
	sharedscripts
	postrotate
		/etc/init.d/inetutils-syslogd reload >/dev/null
	endscript
}
END

	invoke-rc.d inetutils-syslogd start
}

########################################################################
# DNMP Environments
########################################################################
function install_mysql {
	# Install the MariaDB packages
	check_install mysqld mariadb-server
	check_install mysql mariadb-client

	invoke-rc.d mysql stop
	# all the related files.
	cat > /etc/mysql/conf.d/actgod.cnf <<END
[mysqld]
key_buffer_size = 8M
query_cache_size = 0
END
	invoke-rc.d mysql start

	# Generating a new password for the root user.
	passwd=`get_password root@mysql`
	mysqladmin password "$passwd"
	cat > ~/.my.cnf <<END
[client]
user = root
password = $passwd
END
	chmod 600 ~/.my.cnf
}

function install_nginx {
	check_install nginx nginx
	
	# Need to increase the bucket size for Debian 5.
	if [ ! -d /etc/nginx ];
		then
		mkdir /etc/nginx
	fi
	if [ ! -d /etc/nginx/conf.d ];
		then
		mkdir /etc/nginx/conf.d
	fi

	sed -i s/'^worker_processes [0-9];'/'worker_processes 1;'/g /etc/nginx/nginx.conf
	sed -i s/'^user  nginx;'/'user  www-data;'/g /etc/nginx/nginx.conf
	sed -i s/'# gzip_'/'gzip_'/g /etc/nginx/nginx.conf
	invoke-rc.d nginx restart
	if [ ! -d /var/www ];
		then
		mkdir /var/www
	fi
	cat > /etc/nginx/proxy.conf <<EXND
proxy_connect_timeout 30s;
proxy_send_timeout   90;
proxy_read_timeout   90;
proxy_buffer_size    32k;
proxy_buffers     4 32k;
proxy_busy_buffers_size 64k;
proxy_redirect     off;
proxy_hide_header  Vary;
proxy_set_header   Accept-Encoding '';
proxy_set_header   Host   \$host;
proxy_set_header   Referer \$http_referer;
proxy_set_header   Cookie \$http_cookie;
proxy_set_header   X-Real-IP  \$remote_addr;
proxy_set_header   X-Forwarded-For \$proxy_add_x_forwarded_for;
EXND
}

function install_php {
	service mysql stop
	service nginx stop
        apt-get -q -y  install php-fpm php-mysqlnd php-gd php-mcrypt php-tidy php-curl git curl zip unzip php-dom php-mbstring
	service mysql start
	service nginx start
}

function install_phpmyadmin {
	if [ -z "$1" ]
	then
		die "Usage: `basename $0` phpmyadmin <hostname>"
	fi

	# Downloading the phpmyadmin  latest and greatest distribution.
	mkdir /tmp/phpmyadmin.$$ /var/www/$1
	wget -O - https://www.phpmyadmin.net/downloads/phpMyAdmin-latest-all-languages.tar.gz | \
		tar zxf - -C /tmp/phpmyadmin.$$
	mv /tmp/phpmyadmin.$$/phpMyAdmin* "/var/www/$1/phpMyAdmin"
	rm -rf /tmp/phpmyadmin.$$
	chown -R www-data "/var/www/$1"
	chmod -R 755 "/var/www/$1"

		# Setting up Nginx mapping
	cat > "/etc/nginx/conf.d/$1.conf" <<END
server
	{
		listen       80;
		server_name $1;
		index index.html index.htm index.php default.html default.htm default.php;
		root  /var/www/$1;

	location / {
		try_files \$uri \$uri/ /index.php;
	}

	location ~ \.php$ {
		try_files \$uri =404;
		fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
		include fastcgi_params;
		fastcgi_pass unix:/run/php/php7.0-fpm.sock;
	}

		location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|ico)$
			{
				expires      30d;
			}

		location ~ .*\.(js|css)?$
			{
				expires      30d;
			}

		$al
	}
END

invoke-rc.d nginx reload
	
	ServerAdmin=""
	read -p "Please input Administrator Email Address:" ServerAdmin
	if [ "$ServerAdmin" == "" ]; then
		echo "Administrator Email Address will set to webmaster@example.com!"
		ServerAdmin="webmaster@example.com"
	else
	echo "==========================="
	echo Server Administrator Email="$ServerAdmin"
	echo "==========================="
	fi

cat ~/.my.cnf
}

########################################################################
# START OF PROGRAM
########################################################################
export PATH=/bin:/usr/bin:/sbin:/usr/sbin

function dnmp {
check_sanity
case "$1" in
system)
	remove_unneeded
	update_upgrade
	install_utilities
	install_syslogd
	install_exim4
	;;
*)
	echo 'Usage:' `basename $0` '[option]'
	echo 'Available option:'
	for option in system
	do
		echo '  -' $option
	done
	;;
esac
}

dnmp $1 $2 $3 | tee -a /tmp/dnmp.log